package com.keyroy.game.puzzle_rpg.models.animations;

import java.util.ArrayList;
import java.util.List;

import com.keyroy.game.puzzle_rpg.models.interfaces.AnimationListener;

public class AnimationExecuter {

	private static class Pack {
		private List<Animation> list;
		private List<Animation> backup = new ArrayList<Animation>();
		private Thread thread;
		private AnimationListener listener;
		private int delay;
	}

	public static synchronized void start(List<Animation> list, AnimationListener listener, int delay) {
		if (list != null) {
			Pack pack = new Pack();
			pack.list = list;
			pack.listener = listener;
			pack.delay = delay;
			exe(pack);
		}
	}

	private static synchronized void exe(final Pack pack) {
		if (pack.thread == null || pack.thread.isAlive() == false) {
			pack.thread = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(pack.delay);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
					while (pack.list.size() > 0) {

						if (pack.listener != null) {
							pack.listener.onStart();
						}

						pack.backup.clear();

						for (int i = 0; i < pack.list.size(); i++) {
							Animation animation = pack.list.get(i);
							try {
								if (animation.needExecute()) {
									animation.execute();
									pack.backup.add(animation);
								} else {
									animation.onCompelete();
								}
							} catch (Exception e) {
								animation.onError(e);
							}
						}

						try {
							Thread.sleep(pack.delay);
						} catch (Exception e) {
							e.printStackTrace();
						}

						List<Animation> temp = pack.list;
						pack.list = pack.backup;
						pack.backup = temp;
					}

					try {
						if (pack.listener != null) {
							pack.listener.onComplete();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			pack.thread.start();
		}
	}
}
